import { getUserInfoAPI, loginAPI } from '@/api/user'
import router from '@/router'
import { getToken, removeToken, setToken } from '@/utils/auth'
import { Message } from 'element-ui'

export default {
  namespaced: true,
  state() {
    return {
      token: getToken(),
      userInfo: {}
    }
  },
  mutations: {
    SET_TOKEN(state, token) {
      setToken(token)
      state.token = token
    },
    REMOVE_TOKEN(state, token) {
      removeToken()
      state.token = null
    },
    SET_USERINFO(state, userInfo) {
      state.userInfo = userInfo
    },
    CLEAR_USERINFO(state) {
      state.userInfo = {}
    }
  },
  actions: {
    async login(context, { username, password }) {
      // console.log(username, password)
      const res = await loginAPI({ mobile: username, password })
      context.commit('SET_TOKEN', res)
      Message.success('登录成功')
      router.replace('/')
    },
    logout(context) {
      context.commit('REMOVE_TOKEN')
      context.commit('CLEAR_USERINFO')
    },
    async getUserInfo(context) {
      const res = await getUserInfoAPI()
      context.commit('SET_USERINFO', res)
    }
  }
}

